package com.letianpai.utils;

import java.io.ByteArrayInputStream;

import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.provider.ProviderManager;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.packet.VCard;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import com.letianpai.bean.Msg;
import com.letianpai.db.ChatInformation;
import com.letianpai.db.DBUtiles;

public class ChatUtils {

    /*
     * 添加好友
     */
    public static boolean addUser(Roster roster, String userName, String name) {
        try {
            roster.createEntry(userName, name, null);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 修改密码
    public static boolean changePassword(XMPPConnection connection, String pwd) {
        try {
            connection.getAccountManager().changePassword(pwd);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    // 修改用户昵称
    public static boolean changename(XMPPConnection connection, String name) {
        if (XmppTool.getConnection() == null)
            return false;
        try {
            VCard vcard = new VCard();
            vcard.load(XmppTool.getConnection());
            vcard.setNickName(name);
            vcard.save(XmppTool.getConnection());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取用户昵称
    public static String getname(String user) {
        String name = null;
        if (XmppTool.con == null)
            return null;
        try {
            VCard vcard = new VCard();

            if (user == "" || user == null || user.trim().length() <= 0) {
                return null;
            }
            vcard.load(XmppTool.getConnection(), user + "@"
                    + XmppTool.con.getServiceName());

            if (vcard != null || vcard.getNickName() != null)
                name = vcard.getNickName();
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
        return name;
    }

    // 注销
    public static boolean deleteAccount(XMPPConnection connection) {
        try {
            connection.getAccountManager().deleteAccount();
            return true;
        } catch (Exception e) {
            Log.i("info", e.getMessage());
            return false;
        }
    }

    // 修改头像
    public static boolean changeImage(Bitmap file) {
        if (XmppTool.getConnection() == null)
            return false;
        try {
            VCard vcard = new VCard();
            vcard.load(XmppTool.getConnection());

            byte[] bytes;

            // bytes = getFileBytes(file);
            bytes = ImageTools.bitmapToBytes(file);
            String encodedImage = StringUtils.encodeBase64(bytes);
            vcard.setAvatar(bytes, encodedImage);
            vcard.setEncodedImage(encodedImage);
            vcard.setField("PHOTO", "<TYPE>image/jpg</TYPE><BINVAL>"
                    + encodedImage + "</BINVAL>", true);

            ByteArrayInputStream bais = new ByteArrayInputStream(
                    vcard.getAvatar());
            // FormatTools.getInstance().InputStream2Bitmap(bais);

            vcard.save(XmppTool.getConnection());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }

    // 获取用户头像
    public static Bitmap getUserImage(String user) throws Exception {
        if (XmppTool.con == null)
            return null;
        ByteArrayInputStream bais = null;
        try {
            VCard vcard = new VCard();
            // 加入这句代码，解决No VCard for
            ProviderManager.getInstance().addIQProvider("vCard", "vcard-temp",
                    new org.jivesoftware.smackx.provider.VCardProvider());
            if (user == "" || user == null || user.trim().length() <= 0) {
                return null;
            }
            vcard.load(XmppTool.con, user + "@"
                    + XmppTool.con.getServiceName());

            if (vcard == null || vcard.getAvatar() == null)
                return null;
            bais = new ByteArrayInputStream(vcard.getAvatar());
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return ImageTools.inputStreamToBitmap(bais);
    }

    /**
     * 注册
     *
     * @param account  注册帐号
     * @param password 注册密码
     * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败
     */
    public String regist(String account, String password) {
        if (XmppTool.getConnection() == null)
            return "0";
        Registration reg = new Registration();
        reg.setType(IQ.Type.SET);
        reg.setTo(XmppTool.getConnection().getServiceName());
        // 注意这里createAccount注册时，参数是UserName，不是jid，是"@"前面的部分。
        reg.setUsername(account);
        reg.setPassword(password);
        // 这边addAttribute不能为空，否则出错。所以做个标志是android手机创建的吧！！！！！
        reg.addAttribute("android", "geolo_createUser_android");
        PacketFilter filter = new AndFilter(new PacketIDFilter(
                reg.getPacketID()), new PacketTypeFilter(IQ.class));
        PacketCollector collector = XmppTool.getConnection()
                .createPacketCollector(filter);
        XmppTool.getConnection().sendPacket(reg);
        IQ result = (IQ) collector.nextResult(SmackConfiguration
                .getPacketReplyTimeout());
        // Stop queuing results停止请求results（是否成功的结果）
        collector.cancel();
        if (result == null) {
            Log.e("regist", "No response from server.");
            return "0";
        } else if (result.getType() == IQ.Type.RESULT) {
            Log.v("regist", "regist success.");
            return "1";
        } else { // if (result.getType() == IQ.Type.ERROR)
            if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
                Log.e("regist", "IQ.Type.ERROR: "
                        + result.getError().toString());
                return "2";
            } else {
                Log.e("regist", "IQ.Type.ERROR: "
                        + result.getError().toString());
                return "3";
            }
        }
    }

    // 保存聊天记录

    public static void saveChat(Context context, Msg myChatMsg, String chatname, String username) {
        // 保存聊天记录
        ChatInformation chatif = new ChatInformation();
        chatif.setChatInformation(Msg.toJson(myChatMsg));
        chatif.setuId(chatname);
        //
        DBUtiles.saveChatInformation(chatif,
                context, username);
    }

    /**
     * 从path中获取图片信息
     *
     * @param path
     * @return
     */
    public static Bitmap decodeBitmap(String path, int size) {
        BitmapFactory.Options op = new BitmapFactory.Options();
        //inJustDecodeBounds
        //If set to true, the decoder will return null (no bitmap), but the out…
        op.inJustDecodeBounds = true;
        Bitmap bmp = BitmapFactory.decodeFile(path, op); //获取尺寸信息
        //获取比例大小
        int wRatio = (int) Math.ceil(op.outWidth / size);
        int hRatio = (int) Math.ceil(op.outHeight / size);
        //如果超出指定大小，则缩小相应的比例
        if (wRatio > 1 && hRatio > 1) {
            if (wRatio > hRatio) {
                op.inSampleSize = wRatio;
            } else {
                op.inSampleSize = hRatio;
            }
        }
        op.inJustDecodeBounds = false;
        bmp = BitmapFactory.decodeFile(path, op);
        return bmp;
    }

}
